set fish_greeting

function posix_source
	for line in (cat $argv)
		set ass (echo $line | sed 's/export //')
		set arr (string split -m1 = $ass)
		if [ $arr[1] = 'PATH' ]
			set -gx PATH ''
			set paths (string split : $arr[2])
			for path in $paths
				set -gx PATH $PATH (eval "echo $path")
			end
		else
			set_var $arr
		end
	end
end

function set_var
	set v (echo $argv[2] | sed -E 's/\$\((.*)\)/\1/')
	if [ $v != $argv[2] ]
		set -gx $argv[1] ($v)
	else if [ (echo $argv[1] | cut -c1) != '#' ]
		set -gx $argv[1] (eval "echo $argv[2]")
	end
end

for name in (cat ~/.config/sh/functions | grep '()' | grep -v '#' | cut -d '(' -f 1)
	function $name
		bash -c ". ~/.config/sh/functions && $_ $argv"
	end
end

if [ -z "$XDG_RUNTIME_DIR" ]
	set -gx XDG_RUNTIME_DIR "/tmp/$(id -u)-runtime-dir"
	if ! [ -d "$XDG_RUNTIME_DIR" ]
		mkdir "$XDG_RUNTIME_DIR"
		chmod 700 "$XDG_RUNTIME_DIR"
	end
end

. ~/.config/sh/aliases
if [ "$WAYLAND_DISPLAY" != "" ]
	posix_source ~/.config/sh/variables.wayland
end
posix_source ~/.config/sh/variables.(hostname)
posix_source ~/.config/sh/variables

if [ -f /tmp/ssh-agent.fish ]
	. /tmp/ssh-agent.fish >/dev/null
else
	if [ (hostname) != 'localhost' ]  # Marvin w/o root
		ssh-agent -c >/tmp/ssh-agent.fish
	end
end

if [ -f /tmp/dbus.fish ]
	. /tmp/dbus.fish >/dev/null
end

if ! pgrep glider >/dev/null
	glider -listen socks5://:10080 -forward wss://shell.apiote.xyz &
	disown
end

umask 077

if [ (tty) = "/dev/tty1" ] && which sway >/dev/null 2>&1
	posix_source ~/.config/sh/variables.wayland
	exec dbus-run-session -- sway
end

# TODO every 6h and token is OK
# curl -s 8.8.8.8 && drunk sync && echo 'water synced'
